﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Threading;
using System.Windows.Forms;
using System.Drawing;
using System.ComponentModel;
using System.Reflection;
using System.IO;
using System.ServiceProcess;
using System.Net;

using PersistenceObject.Framework;
using PersistenceObject.Framework.Expressions;

using FundSms.Server.Model;
using FundSms.SmsLib;

using PostMsg_Net;

namespace FundSms.Server.Channel.XuanWu
{
    public class Program : ServiceBase
    {
        private static readonly string DataKey = "Sms";

        //企业列表
        private static Dictionary<string,Enterprise> Enterprises;
        //当前通道企业列表
        private static IList<EnterpriseChannel> ChannelEnterprises;

        //广州玄武帐号映射
        private static Dictionary<string, GZXuanWuMapping> Mapping;

        //定时清理控制台
        private static System.Timers.Timer timerConsole = new System.Timers.Timer();
        //定时更新企业数据
        private static System.Timers.Timer timerEnterprise = new System.Timers.Timer();
        //定时更新通道企业数据
        private static System.Timers.Timer timerChannelEnterprise = new System.Timers.Timer();
        //定时更新映射
        private static System.Timers.Timer timerMapping = new System.Timers.Timer();

        private static int RefreshConsoleTime = Convert.ToInt32(ConfigurationManager.AppSettings["RefreshConsoleTime"]) * 1000;
        private static int RefreshEnterpriseTime = Convert.ToInt32(ConfigurationManager.AppSettings["RefreshEnterpriseTime"]) * 1000;
        private static int RefreshMapTime = Convert.ToInt32(ConfigurationManager.AppSettings["RefreshMapTime"]) * 1000;
        private static int RefreshChannelTime = Convert.ToInt32(ConfigurationManager.AppSettings["RefreshChannelTime"]) * 1000;

        private static int SleepTime = Convert.ToInt32(ConfigurationManager.AppSettings["SleepTime"]);
        private static int ReceiveSleepTime = Convert.ToInt32(ConfigurationManager.AppSettings["ReceiveSleepTime"]) * 1000;
        private static int TransferSmsCount = Convert.ToInt32(ConfigurationManager.AppSettings["TransferSmsCount"]);
        private static int SupportEnterpriseCount = Convert.ToInt32(ConfigurationManager.AppSettings["SupportEnterpriseCount"]);
        private static string ChannelCode = ConfigurationManager.AppSettings["ChannelCode"];

        private static int Debug = 0;

        private static string ServiceRealName = ConfigurationManager.AppSettings["ServiceName"];
        private static string ServiceDisPlayName = ConfigurationManager.AppSettings["ServiceDisPlayName"];
        private static string ServiceDescription = ConfigurationManager.AppSettings["ServiceDescription"];

        private static bool LogToFile = ConfigurationManager.AppSettings["LogToFile"] == "1" ? true : false;

        private static string ServerIP = ConfigurationManager.AppSettings["ServerIP"];
        private static string ServerPort = ConfigurationManager.AppSettings["ServerPort"];

        private static object obj = new object();

        //定义发送线程
        private static Thread[] threadsend;
        //定义上行线程
        private static Thread threadmo;

        //当前的企业数
        private static int CurrentEnterpriseCount;
        //是否处于停止服务状态下
        private static bool Stopped = false;
        //判断线程是否已经跳出循环
        private static bool Exit = false;

        private static Dictionary<string, bool> DicStatus = new Dictionary<string, bool>();

        //服务所在路径
        private static string ServicePath = Application.ExecutablePath;
        private static string ServiceDirectory = Path.GetDirectoryName(ServicePath);

        //短信发送实例

        #region 应用程序入口
        static void Main(string[] args)
        {
            Thread.GetDomain().UnhandledException += new UnhandledExceptionEventHandler(Program_UnhandledException);
            Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);

            bool exists = ServiceControl.CheckService(ServiceRealName);

            if (args.Length == 0)
            {
                ServiceBase.Run(new ServiceBase[] { new Program() });
            }
            else
            {
                string parm = args[0].ToLower();

                switch (parm)
                {
                    case "-debug":
                    case "/debug":

                        Debug = 1;

                        if (exists)
                        {
                            ServiceControllerStatus status = ServiceControl.GetServiceStatus(ServiceRealName);

                            if (status != ServiceControllerStatus.Stopped)
                            {
                                Console.WriteLine(GetDateTime() + ServiceRealName + " 服务正在运行，无法进入调试状态。请先停止该服务");
                                Console.ReadLine();
                            }
                            else
                            {
                                InitilizeCompoment();
                            }
                        }
                        else
                        {
                            InitilizeCompoment();
                        }


                        break;

                    case "-install":
                    case "-setup":
                    case "/install":
                    case "/setup":

                        if (exists)
                        {
                            Console.WriteLine(GetDateTime() + ServiceRealName + " 服务已经存在，如果您想升级服务，请先卸载该服务");
                            Console.ReadLine();
                        }
                        else
                        {
                            Console.WriteLine(GetDateTime() + ServicePath);

                            bool result = ServiceControl.InstallService(ServicePath, ServiceRealName, ServiceDisPlayName, ServiceDescription);

                            if (result)
                            {
                                Console.WriteLine(GetDateTime() + "服务安装成功");
                                Console.WriteLine(GetDateTime() + "正在启动服务...");

                                ServiceControl.StartService(ServiceRealName);

                                while (!(ServiceControl.GetServiceStatus(ServiceRealName) == ServiceControllerStatus.Running))
                                {
                                    Thread.Sleep(SleepTime);
                                }

                                Console.WriteLine(GetDateTime() + "服务已经启动");
                            }
                            else
                            {
                                Console.WriteLine(GetDateTime() + "服务安装失败");
                            }

                            Console.ReadLine();
                        }
                        break;

                    case "-uninstall":
                    case "-remove":
                    case "/uninstall":
                    case "/remove":

                        if (!exists)
                        {
                            Console.WriteLine(GetDateTime() + ServiceRealName + " 服务尚未安装");
                        }
                        else
                        {
                            bool result = ServiceControl.UnInstallService(ServiceRealName);

                            if (!result)
                            {
                                Console.WriteLine(GetDateTime() + "服务卸载失败");
                            }
                            else
                            {
                                Console.WriteLine(GetDateTime() + "服务卸载成功");
                            }
                        }

                        Console.ReadLine();

                        break;

                }

            }
        }

        static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            Output("未处理A：" + e.Exception.Message, ConsoleColor.Red, true);
        }

        static void Program_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            if (e.ExceptionObject is System.Exception)
            {
                Output("未处理P：" + ((System.Exception)e.ExceptionObject).Message, ConsoleColor.Red, true);
            }

        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {

            }

            base.Dispose(disposing);
        }

        public Program()
        {
            base.ServiceName = ServiceRealName;
            base.AutoLog = true;
        }

        #endregion

        #region 初始化应用程序
        /// <summary>
        /// 初始化应用程序
        /// </summary>
        private static void InitilizeCompoment()
        {
            if (Debug == 1)
            {
                Console.Title = ServiceDisPlayName;
            }

            //设定用户信息
            Enterprises = GetEnterprise();
            ChannelEnterprises = GetChannelEnterprise();
            Mapping = GetGZXuanWuMapping();

            Output("载入初始数据",true);

            //设置初始企业数
            CurrentEnterpriseCount = ChannelEnterprises.Count;

            Output("当前通道企业数：" + CurrentEnterpriseCount);
            Output("当前映射数：" + Mapping.Count);

            //初始化定时器
            InitilizeTimer();

            Output("初始化定时器",true);

            if (CurrentEnterpriseCount > SupportEnterpriseCount)
            {
                Output("该通道企业超过最大支持数" + SupportEnterpriseCount, true);
                return;
            }

            //初始化线程
            threadsend = new Thread[SupportEnterpriseCount];

            DicStatus.Clear();

            for(int i=0;i<ChannelEnterprises.Count;i++)
            {
                DicStatus.Add(ChannelEnterprises[i].EnterpriseCode, false);

                threadsend[i] = new Thread(new ParameterizedThreadStart(SendSms));
                threadsend[i].Name = ChannelEnterprises[i].EnterpriseCode;
                threadsend[i].Start(ChannelEnterprises[i].EnterpriseCode);
            }

            threadmo = new Thread(ReceiveMO);
            threadmo.Start();

            Output("工作线程初始化",true);

            if (Debug == 1)
            {
                Console.ReadLine();
            }
        }
        #endregion

        #region 业务逻辑
        private static void SendSms(object o)
        {
            string enterprisecode = o.ToString();
            int retrynumber = 0;
            string threadname = enterprisecode;
            PostMsg msg = new PostMsg("", "");

            //初始化短信网关
            if (ServerIP != string.Empty && ServerPort != string.Empty)
            {
                msg.GatewayServer.Address = IPAddress.Parse(ServerIP);
                msg.GatewayServer.Port = int.Parse(ServerPort);
            }

            IList<Channel_HZUNICOM> list = null;

            while (true)
            {
                //如果处于停止服务请求下
                if (Stopped)
                {
                    lock (obj)
                    {
                        DicStatus[threadname] = true;
                    }
                    //跳出循环
                    break;
                }

                if (!Enterprises.ContainsKey(enterprisecode))
                {
                    Thread.Sleep(SleepTime);

                    continue;
                }

                retrynumber = Enterprises[enterprisecode].RetryNumber;

                try
                {
                    //不重发
                    if (retrynumber == -1)
                    {
                        list = QueryOperate<Channel_HZUNICOM>.Create(DataKey).From(new Table("SMS_Channel_" + ChannelCode)).Top(TransferSmsCount).Where(Channel_HZUNICOM._SmsStatus == 0 & Channel_HZUNICOM._EnterpriseCode == enterprisecode & Channel_HZUNICOM._ErrorNumber == 0).OrderBy(Channel_HZUNICOM._LogID).List();
                    }
                    //无限制重发
                    else if (retrynumber == 0)
                    {
                        list = QueryOperate<Channel_HZUNICOM>.Create(DataKey).From(new Table("SMS_Channel_" + ChannelCode)).Top(TransferSmsCount).Where(Channel_HZUNICOM._SmsStatus == 0 & Channel_HZUNICOM._EnterpriseCode == enterprisecode).OrderBy(Channel_HZUNICOM._ErrorNumber, Channel_HZUNICOM._LogID).List();
                    }
                    //限制重发
                    else
                    {
                        list = QueryOperate<Channel_HZUNICOM>.Create(DataKey).From(new Table("SMS_Channel_" + ChannelCode)).Top(TransferSmsCount).Where(Channel_HZUNICOM._SmsStatus == 0 & Channel_HZUNICOM._EnterpriseCode == enterprisecode & Channel_HZUNICOM._ErrorNumber <= retrynumber).OrderBy(Channel_HZUNICOM._ErrorNumber, Channel_HZUNICOM._LogID).List();
                    }
                }
                catch (Exception e)
                {
                    Output(e.Message + "\r\n" + e.StackTrace, ConsoleColor.Red,true);

                    Output("选择本地待发数据遇到错误以后已经忽略错误，跳过本次处理，继续运行", ConsoleColor.Red, true);

                    Thread.Sleep(SleepTime);

                    continue;
                }

                if (list.Count > 0)
                {
                    foreach (Channel_HZUNICOM sms in list)
                    {
                        if (Mapping.ContainsKey(sms.EnterpriseCode))
                        {
                            string username = Mapping[sms.EnterpriseCode].UserName;
                            string password = Mapping[sms.EnterpriseCode].Password;

                            msg.SetUser(username, password);

                            int result = -88;

                            DateTime dt = DateTime.Now;

                            try
                            {
                                result = msg.Post(sms.Mobile, sms.Content, "");

                            }
                            catch (Exception e)
                            {
                                Output("通道错误："+e.Message + "\r\n" + e.StackTrace, ConsoleColor.Red, true);

                                Output("发送到远程通道遇到错误以后已经忽略错误，跳过本次处理，继续运行", ConsoleColor.Red, true);

                                try
                                {

                                    if (retrynumber == -1)
                                    {
                                        UpdateOperate<Channel_HZUNICOM>.Create(DataKey).From((new Table("SMS_Channel_" + ChannelCode))).Fields(
                                                FieldValue.Create(String.Format("{0}={0}+1", Channel_HZUNICOM._ErrorNumber)),
                                                FieldValue.Create(Channel_HZUNICOM._SmsStatus, -1),
                                                FieldValue.Create(Channel_HZUNICOM._SmsStatusRemark, "c")
                                                ).Where(Channel_HZUNICOM._LogID == sms.LogID).Execute();
                                    }
                                    else if (retrynumber == 0)
                                    {
                                        UpdateOperate<Channel_HZUNICOM>.Create(DataKey).From((new Table("SMS_Channel_" + ChannelCode))).Fields(
                                                FieldValue.Create(String.Format("{0}={0}+1", Channel_HZUNICOM._ErrorNumber))).Where(Channel_HZUNICOM._LogID == sms.LogID).Execute();
                                    }
                                    else
                                    {
                                        //更新错误次数
                                        if (sms.ErrorNumber < retrynumber)
                                        {
                                            UpdateOperate<Channel_HZUNICOM>.Create(DataKey).From((new Table("SMS_Channel_" + ChannelCode))).Fields(
                                                    FieldValue.Create(String.Format("{0}={0}+1", Channel_HZUNICOM._ErrorNumber))).Where(Channel_HZUNICOM._LogID == sms.LogID).Execute();
                                        }
                                        else
                                        {
                                            UpdateOperate<Channel_HZUNICOM>.Create(DataKey).From((new Table("SMS_Channel_" + ChannelCode))).Fields(
                                                    FieldValue.Create(String.Format("{0}={0}+1", Channel_HZUNICOM._ErrorNumber)),
                                                    FieldValue.Create(Channel_HZUNICOM._SmsStatus, -1),
                                                    FieldValue.Create(Channel_HZUNICOM._SmsStatusRemark, "c")
                                                    ).Where(Channel_HZUNICOM._LogID == sms.LogID).Execute();
                                        }
                                    }
                                }
                                catch (Exception e1)
                                {
                                    Output("通道错误后的本地错误次数更新出错：" + e1.Message + "\r\n" + e1.StackTrace, ConsoleColor.Red, true);
                                    Output("通道错误后的本地错误次数更新出错，本次错误次数没累加", ConsoleColor.Red, true);
                                }

                                Thread.Sleep(SleepTime);

                                continue;
                            }

                            TimeSpan ts = DateTime.Now - dt;

                            Output("[" + sms.EnterpriseCode + "][" + sms.Mobile + "][" + result.ToString() + "][" + sms.ErrorNumber.ToString() + "][" + ts.TotalSeconds.ToString("0.000") + "] " + sms.Content);

                            try
                            {

                                if (result == 0)
                                {
                                    UpdateOperate<Channel_HZUNICOM>.Create(DataKey).From((new Table("SMS_Channel_" + ChannelCode))).Fields(FieldValue.Create(Channel_HZUNICOM._SmsStatus, 2)).Where(Channel_HZUNICOM._LogID == sms.LogID).Execute();
                                }
                                else
                                {
                                    if (retrynumber == -1)
                                    {
                                        UpdateOperate<Channel_HZUNICOM>.Create(DataKey).From((new Table("SMS_Channel_" + ChannelCode))).Fields(
                                            FieldValue.Create(Channel_HZUNICOM._SmsStatus, -1),
                                            FieldValue.Create(String.Format("{0}={0}+1", Channel_HZUNICOM._ErrorNumber)),
                                            FieldValue.Create(Channel_HZUNICOM._SmsStatusRemark, "xw:" + result.ToString())
                                        ).Where(Channel_HZUNICOM._LogID == sms.LogID).Execute();
                                    }
                                    else if (retrynumber == 0)
                                    {
                                        UpdateOperate<Channel_HZUNICOM>.Create(DataKey).From((new Table("SMS_Channel_" + ChannelCode))).Fields(
                                            FieldValue.Create(String.Format("{0}={0}+1", Channel_HZUNICOM._ErrorNumber))
                                        ).Where(Channel_HZUNICOM._LogID == sms.LogID).Execute();
                                    }
                                    else
                                    {
                                        if (sms.ErrorNumber < retrynumber)
                                        {
                                            UpdateOperate<Channel_HZUNICOM>.Create(DataKey).From((new Table("SMS_Channel_" + ChannelCode))).Fields(
                                                FieldValue.Create(String.Format("{0}={0}+1", Channel_HZUNICOM._ErrorNumber))
                                            ).Where(Channel_HZUNICOM._LogID == sms.LogID).Execute();
                                        }
                                        else
                                        {
                                            UpdateOperate<Channel_HZUNICOM>.Create(DataKey).From((new Table("SMS_Channel_" + ChannelCode))).Fields(
                                            FieldValue.Create(Channel_HZUNICOM._SmsStatus, -1),
                                            FieldValue.Create(String.Format("{0}={0}+1", Channel_HZUNICOM._ErrorNumber)),
                                            FieldValue.Create(Channel_HZUNICOM._SmsStatusRemark, "xw:" + result.ToString())
                                            ).Where(Channel_HZUNICOM._LogID == sms.LogID).Execute();
                                        }
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                Output(e.Message + "\r\n" + e.StackTrace, ConsoleColor.Red,true);
                                Output("更新本地通道状态遇到错误以后已经忽略错误，跳过本次处理，继续运行", ConsoleColor.Red, true);
                            }
                        }
                    }
                }

                Thread.Sleep(SleepTime);
            }

        }

        private static void ReceiveMO()
        {
            PostMsg sms = new PostMsg(string.Empty, string.Empty);
            MO mo = new MO();

            //初始化短信网关
            if (ServerIP != string.Empty && ServerPort != string.Empty)
            {
                sms.GatewayServer.Address = IPAddress.Parse(ServerIP);
                sms.GatewayServer.Port = int.Parse(ServerPort);
            }

            while (true)
            {
                //如果处于停止服务请求下
                if (Stopped)
                {
                    Exit = true;
                    //跳出循环
                    break;
                }

                foreach (GZXuanWuMapping map in Mapping.Values)
                {
                    sms.SetUser(map.UserName, map.Password);

                    MOMessage[] msglist = null;

                    try
                    {
                        msglist = sms.GetMOMessage();
                    }
                    catch (Exception e)
                    {
                        Output("上行错误：" + e.Message + "\r\n" + e.StackTrace, ConsoleColor.Red, true);
                        Output("接收远程上行数据遇到错误以后已经忽略错误，跳过本次处理，继续运行", ConsoleColor.Red, true);
                    }

                    if (msglist != null && msglist.Length > 0)
                    {
                        for (int i = 0; i < msglist.Length; i++)
                        {
                            mo.ChannelCode = ChannelCode;
                            mo.Content = msglist[i].MsgContent;
                            mo.CreateDate = DateTime.Now;
                            mo.EnterpriseCode = map.EnterpriseCode;
                            mo.Mobile = msglist[i].SrcTerminalId;
                            mo.ServiceCode = msglist[i].DestId;
                            mo.Ready1 = string.Empty;
                            mo.Ready2 = string.Empty;
                            mo.Ready3 = string.Empty;
                            mo.Ready4 = 0;
                            mo.Ready5 = false;
                            mo.Status = 0;

                            try
                            {
                                InsertOperate<MO>.Create(DataKey).Execute(mo);
                            }
                            catch (Exception e)
                            {
                                Output(e.Message + "\r\n" + e.StackTrace, ConsoleColor.Red, true);
                                Output("插入本地上行数据遇到错误以后已经忽略错误，跳过本次处理，继续运行", ConsoleColor.Red, true);
                            }

                            Output("[" + map.EnterpriseCode + "][" + mo.Mobile + "]" + mo.Content);
                        }
                    }

                    Thread.Sleep(SleepTime);
                }

                Thread.Sleep(ReceiveSleepTime);
            }
        }

        /// <summary>
        /// 定时管理线程
        /// </summary>
        private static void ManageThreads()
        {
            //判断是否有新企业
            if (CurrentEnterpriseCount < ChannelEnterprises.Count)
            {
                if (ChannelEnterprises.Count <= SupportEnterpriseCount)
                {
                    int dif = ChannelEnterprises.Count - CurrentEnterpriseCount;

                    for (int i = 0; i < dif; i++)
                    {
                        threadsend[CurrentEnterpriseCount + i] = new Thread(new ParameterizedThreadStart(SendSms));
                        threadsend[CurrentEnterpriseCount + i].Name = ChannelEnterprises[CurrentEnterpriseCount + i].EnterpriseCode;
                        threadsend[CurrentEnterpriseCount + i].Start(ChannelEnterprises[CurrentEnterpriseCount + i].EnterpriseCode);

                        DicStatus.Add(ChannelEnterprises[CurrentEnterpriseCount + i].EnterpriseCode, false);
                    }

                    Output("新增通道企业数：" + dif, true);

                    CurrentEnterpriseCount = ChannelEnterprises.Count;

                    Output("当前通道企业数：" + CurrentEnterpriseCount, true);
                }
                else
                {
                    Output("当前通道企业数：" + ChannelEnterprises.Count + "，超过上限", true);
                }

            }

        }
        #endregion

        #region 初始化服务设置
        protected override void OnStart(string[] args)
        {
            InitilizeCompoment();
        }

        protected override void OnStop()
        {
            //停止定时器
            timerConsole.Enabled = false;
            timerEnterprise.Enabled = false;

            //通知线程结束循环
            Stopped = true;

            while (!Exit)
            {
                Thread.Sleep(SleepTime);
            }

            while (!AllStop())
            {
                Thread.Sleep(SleepTime);
            }
        }

        /// <summary>
        /// 判断工作线程是否已经都停止了
        /// </summary>
        /// <returns></returns>
        private static bool AllStop()
        {
            try
            {
                lock (obj)
                {
                    foreach (bool value in DicStatus.Values)
                    {
                        if (!value)
                        {
                            return false;
                        }
                    }
                }

                return true;
            }
            catch (Exception e)
            {
                Output(e.Message + "\r\n" + e.StackTrace, ConsoleColor.Red, true);

                return false;
            }
        }
        #endregion

        #region 初始化定时器
        /// <summary>
        /// 初始化定时器
        /// </summary>
        private static void InitilizeTimer()
        {
            // 定时清理控制台
            timerConsole.Interval = RefreshConsoleTime;
            timerConsole.Enabled = true;
            timerConsole.Elapsed += new System.Timers.ElapsedEventHandler(timerConsole_Elapsed);
            timerConsole.AutoReset = true;

            //定时刷新企业数据
            timerEnterprise.Interval = RefreshEnterpriseTime;
            timerEnterprise.Enabled = true;
            timerEnterprise.Elapsed += new System.Timers.ElapsedEventHandler(timerEnterprise_Elapsed);
            timerEnterprise.AutoReset = true;

            //定时刷新企业数据
            timerMapping.Interval = RefreshMapTime;
            timerMapping.Enabled = true;
            timerMapping.Elapsed += new System.Timers.ElapsedEventHandler(timerMapping_Elapsed);
            timerMapping.AutoReset = true;

            timerChannelEnterprise.Interval = RefreshChannelTime;
            timerChannelEnterprise.Enabled = true;
            timerChannelEnterprise.Elapsed += new System.Timers.ElapsedEventHandler(timerChannelEnterprise_Elapsed);
            timerChannelEnterprise.AutoReset = true;
        }

        static void timerChannelEnterprise_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            IList<EnterpriseChannel> listenterprise = GetChannelEnterprise();

            if (!listenterprise.Equals(ChannelEnterprises))
            {
                try
                {
                    ChannelEnterprises = listenterprise;

                    Output("通道企业数据已更新", true);

                    ManageThreads();
                }
                catch
                {
                }
            }
        }

        static void timerMapping_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            Dictionary<string, GZXuanWuMapping> dic = GetGZXuanWuMapping();

            if (!dic.Equals(Mapping))
            {
                try
                {
                    Mapping = dic;

                    Output("企业映射已更新",true);
                }
                catch
                {
                }
            }
        }

        static void timerEnterprise_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            Dictionary<string,Enterprise> listenterprise = GetEnterprise();

            if (!listenterprise.Equals(Enterprises))
            {
                try
                {
                    Enterprises = listenterprise;

                    Output("企业数据已更新",true);
                }
                catch
                {
                }
            }
        }

        static void timerConsole_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (Debug == 1)
            {
                Console.Clear();
                Output("控制台已更新");
            }
        }
        #endregion

        #region 数据源
        /// <summary>
        /// 获得所有企业
        /// </summary>
        /// <returns></returns>
        private static Dictionary<string,Enterprise> GetEnterprise()
        {
            Dictionary<string, Enterprise> dic = new Dictionary<string, Enterprise>();

            IList<Enterprise> listenterprise = null;

            try
            {
                listenterprise = QueryOperate<Enterprise>.Create(DataKey).Where(Enterprise._EnterpriseStatus == "normal").OrderBy(Enterprise._EnterpriseID).List();

                foreach (Enterprise e in listenterprise)
                {
                    dic.Add(e.EnterpriseCode, e);
                }

                return dic;
            }
            catch (Exception e)
            {
                Output(e.Message + "\r\n" + e.StackTrace, ConsoleColor.Red, true);
            }

            return null;
        }

        /// <summary>
        /// 获得使用该通道的企业
        /// </summary>
        /// <returns></returns>
        private static IList<EnterpriseChannel> GetChannelEnterprise()
        {
            IList<EnterpriseChannel> listenterprise = null;

            try
            {
                listenterprise = QueryOperate<EnterpriseChannel>.Create(DataKey).Where(EnterpriseChannel._ChannelCode == ChannelCode).List();
            }
            catch (Exception e)
            {
                Output(e.Message + "\r\n" + e.StackTrace, ConsoleColor.Red, true);
            }

            return listenterprise;
        }

        /// <summary>
        /// 获得广州玄武的帐号映射
        /// </summary>
        /// <returns></returns>
        private static Dictionary<string, GZXuanWuMapping> GetGZXuanWuMapping()
        {
            Dictionary<string, GZXuanWuMapping> dic = new Dictionary<string, GZXuanWuMapping>();

            IList<GZXuanWuMapping> list = QueryOperate<GZXuanWuMapping>.Create(DataKey).List();

            foreach (GZXuanWuMapping map in list)
            {
                dic.Add(map.EnterpriseCode, map);
            }

            return dic;
        }
        #endregion

        #region 调试辅助逻辑
        private static string GetDateTime()
        {
            return "[" + DateTime.Now.ToString("HH:mm:ss") + "] ";
        }

        private static void Output(string msg)
        {
            lock (obj)
            {
                if (Debug == 1)
                {
                    Console.WriteLine(GetDateTime() + msg);
                }
            }

        }

        private static void Output(string msg, bool log)
        {
            lock (obj)
            {
                if (Debug == 1)
                {
                    Console.WriteLine(GetDateTime() + msg);
                }

                if (log)
                {
                    if (LogToFile)
                    {
                        Log.WriteToFile(ServiceDirectory + @"\log_" + DateTime.Now.ToString("yyyyMMdd") + ".txt", GetDateTime() + msg);
                    }
                }
            }

        }

        private static void Output(string msg, ConsoleColor color)
        {
            lock (obj)
            {
                if (Debug == 1)
                {
                    Console.ForegroundColor = color;
                    Console.WriteLine(GetDateTime() + msg);
                    Console.ResetColor();
                }
            }
        }

        private static void Output(string msg, ConsoleColor color, bool log)
        {
            lock (obj)
            {
                if (Debug == 1)
                {
                    Console.ForegroundColor = color;
                    Console.WriteLine(GetDateTime() + msg);
                    Console.ResetColor();
                }

                if (log)
                {
                    if (LogToFile)
                    {
                        Log.WriteToFile(ServiceDirectory + @"\log_" + DateTime.Now.ToString("yyyyMMdd") + ".txt", GetDateTime() + msg);
                    }
                }
            }
        }
        #endregion
    }
}
